﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ezCloud.Data;
using Nest;
using Newtonsoft.Json;
using ezCloud.Api.Models;
using System.Threading.Tasks;
using ezCloud.Api.Controllers;
using System.Configuration;
using System.Web.Hosting;

namespace ezCloud.Api.Common
{
    public class Elastic
    {
        private static string defaultIndex = ConfigurationSettings.AppSettings["elasticIndex"];
        public static async Task IndexReservationRoom(int id)
        {
            ezCloudDataContext context = new ezCloudDataContext();
            JsonSerializerSettings jsettings = new JsonSerializerSettings
            {
                PreserveReferencesHandling = PreserveReferencesHandling.Objects
            };
            var serializer = JsonSerializer.Create(jsettings);
            
            var reservationRoom = context.ReservationRooms.Where(rr => rr.ReservationRoomId == id).Select(rr => new Common.IndexedReservationRoom { reservation = rr, travellers = rr.TravellersList.ToList(), roomextraserviceitemslist = rr.RoomExtraServiceItemsList.ToList(), rooms = rr.Rooms, Traveller = rr.Travellers }).FirstOrDefault();
            var node = new Uri("http://localhost:9200");
            var settings = new ConnectionSettings(
                    node,
                    defaultIndex: defaultIndex
                );
            var client = new ElasticClient(settings);
            var result = client.Index(reservationRoom, i => i.Index(defaultIndex).Type("reservationroom").Id(id.ToString()).Refresh());
            
        }
        public static async Task IndexRecentSearch(RecentSearchModel model)
        {
            var node = new Uri("http://localhost:9200");
            var settings = new ConnectionSettings(
                    node,
                    defaultIndex: defaultIndex
                );
            var client = new ElasticClient(settings);
            var result = client.Index(model, i => i.Index(defaultIndex).Type("recentsearch").Id(model.id).Refresh());
            return;
        }
        
        public static async Task IndexLastAudit(ezCloudDataContext context)
        {
            var user = Common.UserUtitily.getUserProfile();
            HostingEnvironment.QueueBackgroundWorkItem(t => {
                try {
                    MemoryCacher.ClearStatusCache(user.HotelId);
                    var node = new Uri("http://localhost:9200");
                    var settings = new ConnectionSettings(
                            node,
                            defaultIndex: defaultIndex
                        );
                    var client = new ElasticClient(settings);
                    // var user = Common.UserUtitily.getUserProfile();
                    var entities = context.LastAudit.Entities;
                    context.LastAudit.Date = DateTime.UtcNow;
                    foreach (var entity in entities)
                    {
                        foreach (var ac in entity.Properties)
                        {
                            if (ac.Current != null)
                                ac.Current = ac.Current.ToString();
                            if (ac.Original != null)
                                ac.Original = ac.Original.ToString();

                        }
                    }
                    //Clear Cache
                    //MemoryCacher.ClearStatusCache(user.HotelId);
                    var result = client.Index(context.LastAudit, i => i.Index(defaultIndex).Type("auditlogs").Id(Guid.NewGuid().ToString()).Refresh());
                } catch (Exception ex) { }

            });
            
            return;
        }
        public static async Task IndexErrorLog(ErrorMesssage error)
        {
            
            var node = new Uri("http://localhost:9200");
            var settings = new ConnectionSettings(
                    node,
                    defaultIndex: defaultIndex
                );
            var client = new ElasticClient(settings);
            var result = client.Index(error, i => i.Index(defaultIndex).Type("errorlogs").Id(System.Guid.NewGuid().ToString()).Refresh());
            return;
        }
        public static async Task DeleteAllCache(ezCloudDataContext context)
        {
            
           
            try
            {
                var hotels = context.Hotels.ToList();
                foreach (var item in hotels)
                {
                    MemoryCacher.ClearStatusCache(item.HotelId);
                }
                    
            }
            catch (Exception ex) { }

          

            return;
        }

        public static async Task DeleteCache(int hotelId)
        {


            try
            {
                ezCloudDataContext context = new ezCloudDataContext();
                Hotels hotel = context.Hotels.Where(h => h.HotelId == hotelId).FirstOrDefault();
                if (hotel != null)
                {
                    HotelOwners hotelOwner = context.HotelOwners.Where(ho => ho.UserId == hotel.HotelOwnerId).FirstOrDefault();
                    AspNetUsers userHotelOwner = context.AspNetUsers.Where(u=>u.Id == hotelOwner.UserId).FirstOrDefault();
                    var cache = new MemoryCacher();
                    cache.Delete("USER_PROFILE_" + userHotelOwner.UserName);
                    var staffs = context.Staffs.Where(st => st.HotelId == hotelId).ToList();
                    if (staffs != null)
                    {
                        foreach (Staffs st in staffs)
                        {
                            AspNetUsers userHotelStaff = context.AspNetUsers.Where(u => u.Id == st.UserId).FirstOrDefault();
                            cache.Delete("USER_PROFILE_" + userHotelStaff.UserName);
                        }
                    }
                }                                                
            }
            catch (Exception ex) { }
            return;
        }
    }
}